package com.weixin.webCoding;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @ClassName TcpTest01
 * @Description 测试类
 * @date 2022/2/18 9:34
 * @author: wx
 * @Version 1.0
 */
public class TcpTest01 {

    @Test
    public void client() throws IOException {
        //创建socket连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8002);
        //创建输出流备用
        OutputStream os = socket.getOutputStream();
        //创建文件输入流用于读取文件，以备输出
        FileInputStream fis = new FileInputStream(new File("a.png"));
        byte[] bytes = new byte[1024];
        int len;
        //循环读取文件
        while ((len = fis.read(bytes)) != -1) {
            //使用输出流输出
            os.write(bytes, 0, len);
        }
    }

    @Test
    public void server() throws IOException {
        //使用服务端套接字创建连接
        ServerSocket serverSocket = new ServerSocket(8002);
        //通过服务端套接字1获取客户端套接字
        Socket socket = serverSocket.accept();
        //用于获取客户端传出的输出流
        InputStream is = socket.getInputStream();
        //使用文件流输出文件
        FileOutputStream fos = new FileOutputStream(new File("c.png"));
        byte[] bytes = new byte[1024];
        int len;
        while ((len = is.read(bytes)) != -1) {
            fos.write(bytes, 0, len);
        }
        fos.close();
        is.close();
        serverSocket.close();
    }
}
